package com.dajiangtai.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public final class TimeUtil {
	public static final long DAY = 24L * 60L * 60L * 1000L;
	
	//date 转换为 Timestamp
	public static Timestamp ConvertDateToTimestamp(Date date){
		 if(date==null){
			 date = new Date();
		 }
		 Timestamp ts = new Timestamp(System.currentTimeMillis()); 
		 DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		 String dateStr = sdf.format(date);
		 
		 ts = Timestamp.valueOf(dateStr); 
		return ts; 
	}

	// 获取时间+一周 返回Timestamp
	public static Timestamp getAfterWeekTimestamp() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, 7);
		Timestamp timestamp = new Timestamp(c.getTimeInMillis());
		return timestamp;
	}
		
		
	// 获取当前时间，java.sql.Timestamp类型
	public static Timestamp getCurSQLTimestamp() {
		java.util.Date date = new java.util.Date();
		Timestamp timestamp = new Timestamp(date.getTime());
		return timestamp;
	}

	// 获取当前时间，java.sql.Date类型
	public static java.sql.Date getCurSQLDate() {
		Date date = new Date();
		return new java.sql.Date(date.getTime());
	}
	
	// 提取Timestamp类型的java.sql.Date时间
	public static java.sql.Date getTimestampSQLDate(Timestamp ts) {
		Date date = new Date();
		try {   
            date = ts;   
            //System.out.println(date);   
        } catch (Exception e) {   
            e.printStackTrace();   
        }
		
		return new java.sql.Date(date.getTime());
	}

	// 获取两个Timestamp类型时间的时间差，转为分钟
	public static long getTimestampDiff(Timestamp t1, Timestamp t2) {
		long diff = t1.getTime() - t2.getTime();
		return diff / (1000 * 60);
	}

	// 获取两个Timestamp类型时间相差天数
	public static long getDayDiff(Timestamp t1, Timestamp t2) {
		long diff = 0;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String s1 = df.format(t1);
		String s2 = df.format(t2);
		try {
			Date d1 = df.parse(s1);
			Date d2 = df.parse(s2);
			diff = d1.getTime() - d2.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return diff / DAY;
	}

	// Timestamp加上指定秒数
	public static Timestamp addTimestampBySeconds(Timestamp t, int seconds) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(t);
		cal.add(Calendar.SECOND, seconds);
		return new Timestamp(cal.getTime().getTime());
	}

	// 毫秒转换成Timestamp
	public static Timestamp convertMillionSeconds(String time) {
		long millionSeconds = Long.parseLong(time);
		Timestamp ts = null;
		// 此处转换为Timestamp
		try {
			ts = new Timestamp(millionSeconds);
		} catch (Exception e) {
			ts = new Timestamp(new Date().getTime());
			e.printStackTrace();
		}
		return ts;
	}
}
